package com.rms.recruit_management_system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rms.recruit_management_system.mapper.InterviewMapper;
import com.rms.recruit_management_system.mapper.InterviewVoMapper;
import com.rms.recruit_management_system.mapper.TalentMapper;
import com.rms.recruit_management_system.pojo.Interview;
import com.rms.recruit_management_system.pojo.Positions;
import com.rms.recruit_management_system.pojo.Talent;
import com.rms.recruit_management_system.service.InterviewService;
import com.rms.recruit_management_system.vo.InterviewVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class InterviewServiceImpl extends ServiceImpl<InterviewMapper, Interview> implements InterviewService {

    @Autowired
    private InterviewMapper interviewMapper;
    @Autowired
    private InterviewVoMapper interviewVoMapper;
    @Autowired
    private TalentMapper talentMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String username;
    /**
     * 添加面试信息
     * @param interview
     */
    @Override
    public void addInterview(Interview interview) {
        interview.setCreateTime(LocalDateTime.now());
        interview.setUpdateTime(LocalDateTime.now());
        interviewMapper.insert(interview);
    }

    /**
     * 分页查询面试信息
     * @param pageNo
     * @param pageSize
     * @param search
     * @return
     */
    @Override
    public IPage<Interview> getInterview(int pageNo, int pageSize,String search)  {
        Page<Interview> page=new Page<>(pageNo,pageSize);
        LambdaQueryWrapper<Interview> wrapper= Wrappers.<Interview>lambdaQuery();
        wrapper.ne(Interview::getIsFlag,1);
        if(StrUtil.isNotBlank(search)){
            wrapper.like(Interview::getInterviewTime,search).or().like(Interview::getStatus,search)
                    .or().like(Interview::getPositionName,search).or().like(Interview::getCandidateName,search)
                    .or().like(Interview::getName,search);
        }
        return interviewMapper.selectPage(page,wrapper);
    }

    /**
     * 更新面试信息
     * @param interview
     */
    @Override
    public void updateInterviewStatus(Interview interview) {
        InterviewVo interviewVo=interviewVoMapper.selectEmail(interview.getId());
        InterviewVo interviewVo1=interviewVoMapper.selectInterviewVoById(interview.getId());
        if(interviewVo1.getFeedbackId()>0) {
            interview.setUpdateTime(LocalDateTime.now());
            interviewMapper.updateById(interview);
        }
        if(interviewVo.getEmail()!=null){
                if (interview.getStatus() == 1) {
                    SimpleMailMessage message = new SimpleMailMessage();
                    message.setFrom(username);
                    message.setTo(interviewVo.getEmail());
                    log.info("email: {}", interviewVo.getEmail());
                    message.setSubject("面试结果");
                    message.setText("尊敬的 " + interviewVo.getCandidateName() + "，您好！您已通过面试，被录用为" + interviewVo.getPositionName() + "职位");
                    try {
                        javaMailSender.send(message);
                        log.info("邮件发送成功，收件人: {}", interviewVo.getEmail());
                    } catch (Exception e) {
                        log.error("邮件发送失败，收件人: {}, 错误: {}", interviewVo.getEmail(), e.getMessage());
                    }
                } else if (interview.getStatus() == 2) {
                    SimpleMailMessage message = new SimpleMailMessage();
                    message.setFrom(username);
                    message.setTo(interviewVo.getEmail());
                    log.info("email: {}", interviewVo.getEmail());
                    message.setSubject("面试结果");
                    message.setText("尊敬的 " + interviewVo.getCandidateName() + "，您好！您未能通过面试, 但我们非常荣幸地将您纳入我们公司的人才库，以便在后续有合适的岗位空缺时，能够第一时间与您取得联系！");
                    log.info("interviewVo1: {}", interviewVo1);
                    if(interviewVo1.getFeedbackId()>0){
                        Talent talent=new Talent();
                        talent.setUserId(interviewVo1.getUserId());
                        talent.setInterviewId(interviewVo1.getId());
                        talent.setFeedbackId(interviewVo1.getFeedbackId());
                        talentMapper.insert(talent);
                    }

                    try {
                        javaMailSender.send(message);
                        log.info("邮件发送成功，收件人: {}", interviewVo.getEmail());
                    } catch (Exception e) {
                        log.error("邮件发送失败，收件人: {}, 错误: {}", interviewVo.getEmail(), e.getMessage());
                    }
                } else {
                    SimpleMailMessage message = new SimpleMailMessage();
                    message.setFrom(username);
                    message.setTo(interviewVo.getEmail());
                    log.info("email: {}", interviewVo.getEmail());
                    message.setSubject("面试结果");
                    message.setText("尊敬的 " + interviewVo.getCandidateName() + "，您好！您未能通过面试，被录用为" + interviewVo.getPositionName() + "职位");
                    try {
                        javaMailSender.send(message);
                        log.info("邮件发送成功，收件人: {}", interviewVo.getEmail());
                    } catch (Exception e) {
                        log.error("邮件发送失败，收件人: {}, 错误: {}", interviewVo.getEmail(), e.getMessage());
                    }
                }
            }
    }

    /**
     * 删除面试信息
     * @param id
     */
    @Override
    public void deleteInterview(Integer id) {
        Interview interview=new Interview();
        interview.setIsFlag(1);
        interviewMapper.update(interview,new QueryWrapper<Interview>().eq("id",id));
    }

    /**
     * 获取今日面试数量
     * @return
     */
    @Override
    public Integer getTodayInterviewCount() {
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(23, 59, 59);

        QueryWrapper<Interview> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("interview_date", startOfDay, endOfDay).ne("status", 0);

        return (int) this.count(queryWrapper);
    }

}
